const handler = require('sv-handler')
const {
  isArray
} = require('util')
const db = uniCloud.database()
const dbCmd = db.command

module.exports = {
  async recordList() {
    const {
      user_id
    } = this.params

    if (!user_id) {
      throw handler.result({
        code: 40001,
        message: 'user_id is required'
      })
    }

    const recordRes = await db.collection('sv-exam-record').where({
      "user_id": dbCmd.eq(user_id)
    }).get()

    return handler.result({
      data: recordRes.data,
    })
  },

  async recordAdd() {
    const {
      user_id
    } = this.params

    if (!user_id) {
      throw handler.result({
        code: 40001,
        message: 'user_id is required'
      })
    }

    const findRecord = await db.collection('sv-exam-record').where({
      user_id: dbCmd.eq(user_id)
    }).get()

    const isExist = findRecord.affectedDocs
    if (isExist) {
      throw handler.result({
        code: 40003,
        message: '已存在用户记录，请勿重复创建'
      })
    }

    const recordParams = {
      user_id,
      fav_lib: [],
      fav_exam: [],
      buy_lib: [],
      error_exam: [],
      done_exam: [],
      correct_num: 0,
      error_num: 0
    }

    // 每注册一个用户，则生成唯一的用户信息记录表，在数据库中将user_id设置为唯一键
    const recordRes = await db.collection('sv-exam-record').add(recordParams)

    return handler.result({
      data: recordRes,
    })
  },

  // 收藏题库列表
  async favLibList() {
    const {
      user_id,
    } = this.params

    if (!user_id) {
      throw handler.result({
        code: 40001,
        message: 'user_id is required'
      })
    }

    const recordRes = await db.collection('sv-exam-record').where({
      "user_id": dbCmd.eq(user_id)
    }).field({
      'fav_lib': true
    }).get()

    if (recordRes.data.length < 1) {
      throw handler.result({
        code: 40002,
        message: '未查询到相关记录'
      })
    }

    const favLibRes = await db.collection('sv-exam-libs').where({
      'lib_id': dbCmd.in(recordRes.data[0].fav_lib)
    }).get()

    return handler.result({
      data: favLibRes.data,
      message: '查询成功'
    })
  },

  // 收藏题库添加
  async favLibAdd() {
    const {
      user_id,
      lib_id
    } = this.params

    if (!user_id || !lib_id) {
      throw handler.result({
        code: 40001
      })
    }

    let query = db.collection('sv-exam-record')

    const favLibRes = await query.where({
      "user_id": dbCmd.eq(user_id)
    }).field({
      'fav_lib': true
    }).get()

    if (favLibRes.data[0].fav_lib.some(e => e === lib_id)) {
      throw handler.result({
        code: 40004,
        message: '已收藏该题库'
      })
    }

    const recordRes = await query.where({
      "user_id": dbCmd.eq(user_id)
    }).field({
      'fav_lib': true
    }).update({
      "fav_lib": dbCmd.push(lib_id) // 向数组头部添加元素
    })

    // 收藏量+1
    await db.collection('sv-exam-libs').where({
      'lib_id': dbCmd.eq(lib_id)
    }).update({
      'fav_num': dbCmd.inc(1)
    })

    return handler.result({
      data: recordRes,
      message: '添加收藏成功'
    })
  },

  // 收藏题库移除
  async favLibDelete() {
    const {
      user_id,
      lib_id
    } = this.params

    if (!user_id || !lib_id) {
      throw handler.result({
        code: 40001,
      })
    }

    const favLibRes = await db.collection('sv-exam-record').where({
      "user_id": dbCmd.eq(user_id)
    }).field({
      'fav_lib': true
    }).get()

    if (!favLibRes.data[0].fav_lib.some(e => e === lib_id)) {
      throw handler.result({
        code: 40004,
        message: '未收藏该题库'
      })
    }

    const recordRes = await db.collection('sv-exam-record').where({
      "user_id": dbCmd.eq(user_id),
    }).field({
      'fav_lib': true
    }).update({
      "fav_lib": dbCmd.pull(lib_id)
    })

    // 收藏量-1
    await db.collection('sv-exam-libs').where({
      'lib_id': dbCmd.eq(lib_id)
    }).update({
      'fav_num': dbCmd.inc(-1)
    })

    return handler.result({
      data: recordRes,
      message: '取消收藏成功'
    })
  },

  // 收藏题库清空 - 慎用尽量不用 极其不推荐直接清空收藏
  async favLibClear() {
    const {
      user_id
    } = this.params

    if (!user_id) {
      throw handler.result({
        code: 40001,
        message: 'user_id is required'
      })
    }

    const recordRes = await db.collection('sv-exam-record').where({
      "user_id": dbCmd.eq(user_id),
    }).field({
      'fav_lib': true
    }).update({
      "fav_lib": dbCmd.set([])
    })

    return handler.result({
      data: recordRes.data[0].fav_lib,
      message: '清空收藏成功'
    })
  },

  // 已购题库列表
  async buyLibList() {
    const {
      user_id
    } = this.params

    if (!user_id) {
      throw handler.result({
        code: 40001,
        message: 'user_id is required'
      })
    }

    const recordRes = await db.collection('sv-exam-record').where({
      "user_id": dbCmd.eq(user_id)
    }).field({
      "buy_lib": true
    }).get()

    if (recordRes.data.length < 1) {
      throw handler.result({
        code: 40002,
        message: '未查询到相关记录'
      })
    }

    const buyLibRes = await db.collection('sv-exam-libs').where({
      'lib_id': dbCmd.in(recordRes.data[0].buy_lib)
    }).get();

    return handler.result({
      data: buyLibRes.data,
      message: '查询成功'
    })
  },

  // 已购题库添加
  async buyLibAdd() {
    const {
      user_id,
      lib_id
    } = this.params

    if (!user_id || !lib_id) {
      throw handler.result({
        code: 40001,
      })
    }

    let query = db.collection('sv-exam-record')

    const buyLibRes = await query.where({
      "user_id": dbCmd.eq(user_id)
    }).field({
      "buy_lib": true
    }).get()

    if (buyLibRes.data[0].buy_lib.some(e => e === lib_id)) {
      throw handler.result({
        code: 40004,
        message: '已拥有该题库'
      })
    }

    const recordRes = await query.where({
      "user_id": dbCmd.eq(user_id)
    }).field({
      "buy_lib": true
    }).update({
      "buy_lib": dbCmd.push(lib_id) // 向数组头部添加元素
    })

    // 销售量+1
    await db.collection('sv-exam-libs').where({
      'lib_id': dbCmd.eq(lib_id)
    }).update({
      'sell_num': dbCmd.inc(1)
    })

    return handler.result({
      data: recordRes,
      message: '购买题库成功'
    })
  },

  // 已购题库不提供移除接口，禁止删除已购记录

  // 收藏试题列表
  async favExamList() {
    let {
      user_id,
      from_lib,
      unit,
      pagesize = 20,
      pagenum = 1,
    } = this.params

    if (!user_id) {
      throw handler.result({
        code: 40001,
        message: 'user_id is required'
      })
    }

    // 转换为Number类型
    pagesize = +pagesize
    pagenum = +pagenum

    // 页码不可小于1
    if (pagenum < 1) {
      throw handler.result({
        code: 40001,
        message: 'pagenum不可小于1'
      })
    }

    let favExamRes, pages, total

    const dbJQL = uniCloud.databaseForJQL({
      clientInfo: this.getClientInfo()
    })

    const recordRes = await db.collection('sv-exam-record').where({
      "user_id": dbCmd.eq(user_id)
    }).field({
      'fav_exam': true
    }).get()


    // 构建筛选条件(对象形式)
    const conditions = {}
    conditions.exam_id = dbCmd.in(recordRes.data[0].fav_exam)
    if (from_lib) {
      conditions.from_lib = dbCmd.eq(from_lib)
    }
    if (unit) {
      conditions.unit = dbCmd.eq(unit)
    }

    // 连接表实例
    let query = dbJQL.collection('sv-exam-list').where(conditions)

    if (pagesize < 1) {
      // 全量查询
      favExamRes = await query.get({
        getCount: true
      })
      total = favExamRes.count
      pages = 1
    } else {
      // 分页查询
      favExamRes = await query.skip(pagesize * (pagenum - 1)).limit(pagesize).get({
        getCount: true
      })
      total = favExamRes.count
      pages = Math.ceil(total / pagesize)
    }

    return handler.result({
      data: favExamRes.data,
      total,
      pagesize,
      pagenum,
      pages,
      params: this.params,
      message: '查询成功'
    })
  },

  // 收藏试题添加
  async favExamAdd() {
    const {
      user_id,
      exam_id
    } = this.params

    if (!user_id || !exam_id) {
      throw handler.result({
        code: 40001,
      })
    }

    let query = db.collection('sv-exam-record')

    const favExamRes = await query.where({
      "user_id": dbCmd.eq(user_id)
    }).field({
      'fav_exam': true
    }).get()

    if (favExamRes.data[0].fav_exam.some(e => e === exam_id)) {
      throw handler.result({
        code: 40004,
        message: '已收藏该试题'
      })
    }

    const recordRes = await query.where({
      "user_id": dbCmd.eq(user_id)
    }).field({
      'fav_exam': true
    }).update({
      "fav_exam": dbCmd.push(exam_id) // 向数组头部添加元素
    })

    return handler.result({
      data: recordRes,
      message: '添加收藏成功'
    })
  },

  // 收藏试题移除
  async favExamDelete() {
    const {
      user_id,
      exam_id
    } = this.params

    if (!user_id || !exam_id) {
      throw handler.result({
        code: 40001,
      })
    }

    if (!Array.isArray(exam_id)) {
      const favExamRes = await db.collection('sv-exam-record').where({
        "user_id": dbCmd.eq(user_id)
      }).field({
        'fav_exam': true
      }).get()
      const favExamData = favExamRes.data[0].fav_exam
      if (!favExamData.some(e => e === exam_id)) {
        throw handler.result({
          code: 40004,
          message: '未收藏该试题'
        })
      }
    }

    const recordRes = await db.collection('sv-exam-record').where({
      "user_id": dbCmd.eq(user_id),
    }).field({
      'fav_exam': true
    }).update({
      "fav_exam": Array.isArray(exam_id) ? dbCmd.pull(dbCmd.in(exam_id)) : dbCmd.pull(exam_id)
    })

    return handler.result({
      data: recordRes,
      message: '取消收藏成功'
    })
  },

  // 收藏试题清空
  async favExamClear() {
    const {
      user_id
    } = this.params

    if (!user_id) {
      throw handler.result({
        code: 40001,
        message: 'user_id is required'
      })
    }

    const recordRes = await db.collection('sv-exam-record').where({
      "user_id": dbCmd.eq(user_id),
    }).field({
      'fav_exam': true
    }).update({
      "fav_exam": dbCmd.set([])
    })

    return handler.result({
      data: recordRes.data[0].fav_exam,
      message: '清空收藏成功'
    })
  },

  // 错题列表
  async errorExamList() {
    let {
      user_id,
      from_lib,
      unit,
      pagesize = 20,
      pagenum = 1,
    } = this.params

    if (!user_id) {
      throw handler.result({
        code: 40001,
        message: 'user_id is required'
      })
    }

    // 转换为Number类型
    pagesize = +pagesize
    pagenum = +pagenum

    // 页码不可小于1
    if (pagenum < 1) {
      throw handler.result({
        code: 40001,
        message: 'pagenum不可小于1'
      })
    }

    let errorExamRes, pages, total

    const dbJQL = uniCloud.databaseForJQL({
      clientInfo: this.getClientInfo()
    })

    const recordRes = await db.collection('sv-exam-record').where({
      "user_id": dbCmd.eq(user_id)
    }).field({
      'error_exam': true
    }).get()

    // 构建筛选条件(对象形式)
    const conditions = {}
    conditions.exam_id = dbCmd.in(recordRes.data[0].error_exam)
    if (from_lib) {
      conditions.from_lib = dbCmd.eq(from_lib)
    }
    if (unit) {
      conditions.unit = dbCmd.eq(unit)
    }

    // 连接表实例
    let query = dbJQL.collection('sv-exam-list').where(conditions)

    if (pagesize < 1) {
      // 全量查询
      errorExamRes = await query.get({
        getCount: true
      })
      total = errorExamRes.count
      pages = 1
    } else {
      // 分页查询
      errorExamRes = await query.skip(pagesize * (pagenum - 1)).limit(pagesize).get({
        getCount: true
      })
      total = errorExamRes.count
      pages = Math.ceil(total / pagesize)
    }

    return handler.result({
      data: errorExamRes.data,
      total,
      pagesize,
      pagenum,
      pages,
      params: this.params,
      message: '查询成功'
    })
  },

  // 错题添加
  async errorExamAdd() {
    const {
      user_id,
      exam_id
    } = this.params

    if (!user_id || !exam_id) {
      throw handler.result({
        code: 40001,
      })
    }

    const errorExamRes = await db.collection('sv-exam-record').where({
      "user_id": dbCmd.eq(user_id)
    }).field({
      'error_exam': true
    }).get()

    if (errorExamRes.data[0].error_exam.some(e => e === exam_id)) {
      throw handler.result({
        code: 40004,
        message: '该试题已在错题本中'
      })
    }

    const recordRes = await db.collection('sv-exam-record').where({
      "user_id": dbCmd.eq(user_id)
    }).field({
      'error_exam': true
    }).update({
      "error_exam": dbCmd.push(exam_id) // 向数组头部添加元素
    })

    return handler.result({
      data: recordRes,
      message: '添加错题成功'
    })
  },

  // 错题移除
  async errorExamDelete() {
    const {
      user_id,
      exam_id
    } = this.params

    if (!user_id || !exam_id) {
      throw handler.result({
        code: 40001,
      })
    }

    if (!Array.isArray(exam_id)) {
      const errorExamRes = await db.collection('sv-exam-record').where({
        "user_id": dbCmd.eq(user_id)
      }).field({
        'error_exam': true
      }).get()
      const errorExamData = errorExamRes.data[0].error_exam
      if (!errorExamData.some(e => e === exam_id)) {
        throw handler.result({
          code: 40004,
          message: '该试题未在错题本中'
        })
      }
    }

    const recordRes = await db.collection('sv-exam-record').where({
      "user_id": dbCmd.eq(user_id),
    }).field({
      'error_exam': true
    }).update({
      "error_exam": Array.isArray(exam_id) ? dbCmd.pull(dbCmd.in(exam_id)) : dbCmd.pull(exam_id)
    })

    return handler.result({
      data: recordRes,
      message: '删除错题成功'
    })
  },

  // 错题清空
  async errorExamClear() {
    const {
      user_id
    } = this.params

    if (!user_id) {
      throw handler.result({
        code: 40001,
        message: 'user_id is required'
      })
    }

    const recordRes = await db.collection('sv-exam-record').where({
      "user_id": dbCmd.eq(user_id),
    }).field({
      'error_exam': true
    }).update({
      "error_exam": dbCmd.set([])
    })

    return handler.result({
      data: recordRes.data[0].error_exam,
      message: '清空错题成功'
    })
  },

  // 已做题列表
  async doneExamList() {
    let {
      user_id,
      from_lib,
      unit,
      pagesize = 20,
      pagenum = 1,
    } = this.params

    if (!user_id) {
      throw handler.result({
        code: 40001,
        message: 'user_id is required'
      })
    }

    // 转换为Number类型
    pagesize = +pagesize
    pagenum = +pagenum

    // 页码不可小于1
    if (pagenum < 1) {
      throw handler.result({
        code: 40001,
        message: 'pagenum不可小于1'
      })
    }

    let doneExamRes, pages, total

    const dbJQL = uniCloud.databaseForJQL({
      clientInfo: this.getClientInfo()
    })

    const recordRes = await db.collection('sv-exam-record').where({
      "user_id": dbCmd.eq(user_id)
    }).field({
      'done_exam': true
    }).get()

    // 构建筛选条件(对象形式)
    const conditions = {}
    conditions.exam_id = dbCmd.in(recordRes.data[0].done_exam)
    if (from_lib) {
      conditions.from_lib = dbCmd.eq(from_lib)
    }
    if (unit) {
      conditions.unit = dbCmd.eq(unit)
    }

    // 连接表实例
    let query = dbJQL.collection('sv-exam-list').where(conditions)

    if (pagesize < 1) {
      // 全量查询
      doneExamRes = await query.get({
        getCount: true
      })
      total = doneExamRes.count
      pages = 1
    } else {
      // 分页查询
      doneExamRes = await query.skip(pagesize * (pagenum - 1)).limit(pagesize).get({
        getCount: true
      })
      total = doneExamRes.count
      pages = Math.ceil(total / pagesize)
    }

    return handler.result({
      data: doneExamRes.data,
      total,
      pagesize,
      pagenum,
      pages,
      params: this.params,
      message: '查询成功'
    })
  },

  // 已做题添加
  async doneExamAdd() {
    const {
      user_id,
      exam_id
    } = this.params

    if (!user_id || !exam_id) {
      throw handler.result({
        code: 40001,
      })
    }

    const doneExamRes = await db.collection('sv-exam-record').where({
      "user_id": dbCmd.eq(user_id)
    }).field({
      'done_exam': true
    }).get()

    if (doneExamRes.data[0].done_exam.some(e => e === exam_id)) {
      throw handler.result({
        code: 40004,
        message: '该试题已在做题记录中'
      })
    }

    const recordRes = await db.collection('sv-exam-record').where({
      "user_id": dbCmd.eq(user_id)
    }).field({
      'done_exam': true
    }).update({
      "done_exam": dbCmd.push(exam_id) // 向数组头部添加元素
    })

    return handler.result({
      data: recordRes,
      message: '添加做题记录成功'
    })
  },

  // 已做题不提供移除接口，禁止删除已做题记录

  // 刷题正确统计 - 只会累加，不提供减少和清0
  async correctNumQuery() {
    const {
      user_id
    } = this.params

    if (!user_id) {
      throw handler.result({
        code: 40001,
        message: 'user_id is required'
      })
    }

    const numRes = await db.collection('sv-exam-record').where({
      "user_id": dbCmd.eq(user_id)
    }).field({
      'correct_num': true
    }).get()

    return handler.result({
      data: numRes.data[0].correct_num,
    })
  },

  // 刷题正确+1
  async correctNumInc() {
    const {
      user_id
    } = this.params

    if (!user_id) {
      throw handler.result({
        code: 40001,
        message: 'user_id is required'
      })
    }

    const recordRes = await db.collection('sv-exam-record').where({
      "user_id": dbCmd.eq(user_id)
    }).field({
      'correct_num': true
    }).update({
      'correct_num': dbCmd.inc(1)
    })

    const numRes = await db.collection('sv-exam-record').where({
      "user_id": dbCmd.eq(user_id)
    }).field({
      'correct_num': true
    }).get()

    return handler.result({
      data: {
        ...recordRes,
        result: numRes.data[0].correct_num
      },
    })
  },

  // 刷题错误统计 - 只会累加，不提供减少和清0
  async errorNumQuery() {
    const {
      user_id
    } = this.params

    if (!user_id) {
      throw handler.result({
        code: 40001,
        message: 'user_id is required'
      })
    }

    const numRes = await db.collection('sv-exam-record').where({
      "user_id": dbCmd.eq(user_id)
    }).field({
      'error_num': true
    }).get()

    return handler.result({
      data: numRes.data[0].error_num
    })
  },

  // 刷题错误+1
  async errorNumInc() {
    const {
      user_id
    } = this.params

    if (!user_id) {
      throw handler.result({
        code: 40001,
        message: 'user_id is required'
      })
    }

    const recordRes = await db.collection('sv-exam-record').where({
      "user_id": dbCmd.eq(user_id)
    }).field({
      'error_num': true
    }).update({
      'error_num': dbCmd.inc(1)
    })

    const numRes = await db.collection('sv-exam-record').where({
      "user_id": dbCmd.eq(user_id)
    }).field({
      'error_num': true
    }).get()

    return handler.result({
      data: {
        ...recordRes,
        result: numRes.data[0].error_num
      },
    })
  }
}